﻿namespace TetrisProject.GameObjects
{
    using System;
    using System.Collections.Generic;
    using TetrisProject.Interfaces;

    public class ConsoleRenderer
    {
        private const char BLOCK_SYMBOL = '#';

        private int height;
        private int width;
        private bool[,] field;

        public ConsoleRenderer(int height, int width)
        {
            this.height = height;
            this.width = width;
            this.field = new bool[this.height, this.width];
        }

        public void InsertBlock(IRenderable block)
        {
            int coordX = block.GetTopLeft().X;
            int coordY = block.GetTopLeft().Y;

            var blockBody = block.GetBody();

            for (int i = 0; i < blockBody.GetLength(0); i++)
            {
                for (int j = 0; j < blockBody.GetLength(1); j++)
                {
                    if (coordX + i < this.height && coordY + j < this.width)
                    {
                        this.field[coordX + i, coordY + j] = blockBody[i, j];
                    }
                }
            }
        }

        public void InsertBlockCollection(IList<IRenderable> collection)
        {
            foreach (var block in collection)
            {
                this.InsertBlock(block);
            }
        }

        public void RenderAll()
        {
            for (int i = 0; i < this.field.GetLength(0); i++)
            {
                for (int j = 0; j < this.field.GetLength(1); j++)
                {
                    if (i == this.field.GetLength(0) - 1 && j == this.field.GetLength(1) - 1)
                    {
                        continue;
                    }

                    Console.SetCursorPosition(j, i);
                    if (this.field[i, j])
                    {
                        Console.Write(ConsoleRenderer.BLOCK_SYMBOL);
                    }
                    else
                    {
                        Console.Write(' ');
                    }
                }
            }
        }

        public void ClearBuffer()
        {
            for (int i = 0; i < this.field.GetLength(0); i++)
            {
                for (int j = 0; j < this.field.GetLength(1); j++)
                {
                    this.field[i, j] = false;
                }
            }
        }
    }
}
